package com.sjr.easy.chat.app.interceptor;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Sets;
import com.sjr.easy.chat.app.dto.AppTokenInfo;
import com.sjr.easy.chat.app.enums.AppLoginStatusEnum;
import com.sjr.easy.chat.app.utils.AppTokenManager;
import com.sjr.easy.chat.dto.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;
import java.util.Set;

@Slf4j
@Component
public class AppLoginStatusInterceptor implements HandlerInterceptor {

    private final Set<String> notNeedLoginURLSet = Sets.newHashSet(
            "/app/user/login",
            "/app/user/register",
            "/app/user/getUserHeadPortrait",
            "/app/ws/notify"
    );

    @Autowired
    private AppTokenManager appTokenManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        log.info("url:{}", requestURI);
        if (notNeedLoginURLSet.contains(requestURI) || !requestURI.startsWith("/app")) {
            return true;
        }
        AppTokenInfo appTokenInfo = appTokenManager.getTokenInfo(token);
        if (appTokenInfo == null) {
            response.setContentType("application/json;charset=UTF-8");
            AppLoginStatusEnum tokenTimeout = AppLoginStatusEnum.TokenTimeout;
            response.setHeader("tokenStatusCode", tokenTimeout.getCode().toString());
            response.setHeader("tokenStatusMessage", Hex.encodeHexString(tokenTimeout.getMessage().getBytes(StandardCharsets.UTF_8)));
            response.getWriter().write(JSON.toJSONString(Result.error(tokenTimeout.getCode(), tokenTimeout.getMessage())));
            return false;
        }
        appTokenManager.resetTimeout(token);
        return true;
    }
}
